package com.lagou.module4.dao;

import com.lagou.module4.model.User;
import com.lagou.module4.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImp implements UserDao {
    @Override
    public User userLogin(User user) {
        //1.获取数据库连接
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            connection = DbUtil.getConnection();

            //2 准备sql语句
            String sql = "select * from t_user where userName= ? and passWord = ?";
            //3 执行sql语句并获取结果
            ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPassWord());
            resultSet = ps.executeQuery();
            if (resultSet.next()){
                User tu = new User(resultSet.getString("userName"),resultSet.getString("passWord"));
                return tu;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //4 释放资源
            try {
                DbUtil.closeResource(connection, ps);
                if(null != resultSet) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
